﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Drawing;
using System.IO;
using System.Drawing.Imaging;
using FortuneHeavenBAL;
using FortuneHeavenCommon.DataMap;
using FortuneHeavenDAL;
using System.Web.SessionState;
using FortuneHeaven.Web.Common;

namespace FortuneHeaven.Web.Pages
{
    /// <summary>
    /// ImageHandler 的摘要说明
    /// </summary>
    public class ImageHandler : IHttpHandler, IRequiresSessionState
    {

        public void ProcessRequest(HttpContext context)
        {
            //context.Response.ContentType = "text/plain";
            if (!string.IsNullOrEmpty(context.Request["headid"]) && !string.IsNullOrEmpty(context.Request["headid"].Trim()))
            {
                GetHead(context);
            }
            if (!string.IsNullOrEmpty(context.Request["upload"]))
            {
                UploadCustomHead(context);
            }
            if (!string.IsNullOrEmpty(context.Request["cusheadid"]))
            {
                GetCustomHead(context);
            }
            if (!string.IsNullOrEmpty(context.Request["pureheadid"]))
            {
                GetPureHead(context);
            }

        }

        public void GetCustomHead(HttpContext context)
        {
            string headid = context.Request["cusheadid"].Trim();
            int head = 0;
            int.TryParse(headid, out head);
            CustomFaceBO bo = new CustomFaceBO();
            CustomFace face = bo.GetInfo(head);
            context.Response.ClearContent();
            context.Response.ContentType = "image/Gif";
            if (face != null)
            {
                context.Response.BinaryWrite(face.FaceImage);
            }
            context.Response.End();
        }

        public void UploadCustomHead(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            string newName = Guid.NewGuid().ToString();
            if (AuthorityCenter.CurrentUserID > 0)
            {
                if (context.Request.Files.Count > 0)
                {

                    HttpPostedFile file = context.Request.Files[0];
                    long len = file.InputStream.Length;
                    CustomFaceBO bo = new CustomFaceBO();
                    CustomFace face = new CustomFace();
                    face.Name = Path.GetExtension(file.FileName).ToLower();
                    face.Description = "";
                    face.Time = DateTime.Now;
                    face.FaceImage = new byte[len];
                    context.Request.Files[0].InputStream.Read(face.FaceImage, 0, (int)len);
                    int headid = bo.SaveCustomeFace(face);
                    UserInforBO userbo = new UserInforBO();
                    UserInfor user = userbo.GetUserInfor(AuthorityCenter.CurrentUserID);
                    if (user == null)
                    {
                        user = new UserInfor();
                        user.ID = userbo.GetMaxID();
                        user.FaceID = headid;
                        userbo.Save(user, true);
                    }
                    else
                    {
                        user.FaceID = headid;
                        userbo.Save(user);
                    }
                    context.Response.Clear();
                    context.Response.Write("{'url':'" + VirtualPathUtility.ToAbsolute("~/Pages/ImageHandler.ashx") + "?cusheadid=" + headid.ToString() + "','success':true}");
                    context.Response.End();
                }
                else
                {
                    long len = context.Request.InputStream.Length;
                    CustomFaceBO bo = new CustomFaceBO();
                    CustomFace face = new CustomFace();
                    face.Name = Path.GetExtension(context.Request["qqfile"]).ToLower();
                    face.Description = "";
                    face.Time = DateTime.Now;
                    face.FaceImage = new byte[len];
                    context.Request.InputStream.Read(face.FaceImage, 0, (int)len);
                    int headid = bo.SaveCustomeFace(face);
                    UserInforBO userbo = new UserInforBO();
                    UserInfor user = userbo.GetUserInfor(AuthorityCenter.CurrentUserID);
                    if (user == null)
                    {
                        user = new UserInfor();
                        user.ID = userbo.GetMaxID();
                        user.FaceID = headid;
                        userbo.Save(user, true);
                    }
                    else
                    {
                        user.FaceID = headid;
                        userbo.Save(user);
                    }
                    context.Response.Clear();
                    context.Response.Write("{'url':'" + VirtualPathUtility.ToAbsolute("~/Pages/ImageHandler.ashx") + "?cusheadid=" + headid.ToString() + "','success':true}");
                    context.Response.End();
                }
            }
            else
            {
                context.Response.Clear();
                context.Response.Write("{'success':false}");
                context.Response.End();
            }
        }

        public void GetHead(HttpContext context)
        {
            string tt = context.Request["headid"].Trim();
            string gender = context.Request["gender"].Trim();
            Bitmap head = null;
            Bitmap frame = null;
            Bitmap total = null;
            int headid = 0;
            int.TryParse(tt, out headid);
            try
            {
                if (headid <= 0)
                {
                    GenereateGoldHead(context, gender, ref head, ref frame, ref total);
                }
                else
                {

                    CustomFaceBO bo = new CustomFaceBO();
                    CustomFace face = bo.GetInfo(headid);
                    if (face.FaceImage == null || face.FaceImage.Length == 0)
                    {
                        GenereateGoldHead(context, gender, ref head, ref frame, ref total);
                    }
                    else
                    {

                        frame = new Bitmap(context.Server.MapPath("~/Content/Image/Head/gold.gif"));
                        total = new Bitmap(frame.Size.Width, frame.Size.Height);
                        MemoryStream source = new MemoryStream(face.FaceImage);
                        head = (Bitmap)Bitmap.FromStream(source);
                        using (Graphics gc = Graphics.FromImage(total))
                        {
                            //Brush bursh = Brushes.White;
                            gc.Clear(Color.White);
                            gc.DrawImage(head, 45, 17, 109, 105);
                            gc.DrawImage(frame, 0, 0);
                            gc.Save();
                            using (MemoryStream ms = new MemoryStream())
                            {
                                total.Save(ms, ImageFormat.Bmp);
                                context.Response.ClearContent();
                                context.Response.ContentType = "image/Gif";
                                context.Response.Cache.SetNoStore();
                                context.Response.BinaryWrite(ms.ToArray());
                                context.Response.End();
                            }
                        }
                        context.Response.ClearContent();
                        context.Response.ContentType = "image/Gif";
                        if (face != null)
                        {
                            context.Response.BinaryWrite(face.FaceImage);
                        }
                        context.Response.End();
                        source.Dispose();
                    }
                }
            }
            catch
            {

            }
            finally
            {
                if (head != null)
                {
                    head.Dispose();
                }
                if (frame != null)
                {
                    frame.Dispose();
                }
                if (total != null)
                {
                    total.Dispose();
                }
            }

        }

        private static void GenereateGoldHead(HttpContext context, string gender, ref Bitmap head, ref Bitmap frame, ref Bitmap total)
        {
            if (gender == "2")
            {
                head = new Bitmap(context.Server.MapPath("~/Content/Image/Head/pic_f.gif"));
            }
            else
            {
                head = new Bitmap(context.Server.MapPath("~/Content/Image/Head/pic_m.gif"));
            }
            frame = new Bitmap(context.Server.MapPath("~/Content/Image/Head/gold.gif"));
            total = new Bitmap(frame.Size.Width, frame.Size.Height);

            using (Graphics gc = Graphics.FromImage(total))
            {
                //Brush bursh = Brushes.White;
                gc.Clear(Color.White);
                gc.DrawImage(head, 45, 17, 109, 105);
                gc.DrawImage(frame, 0, 0);
                gc.Save();
                using (MemoryStream ms = new MemoryStream())
                {
                    total.Save(ms, ImageFormat.Bmp);
                    context.Response.ClearContent();
                    context.Response.ContentType = "image/Gif";
                    context.Response.Cache.SetNoStore();
                    context.Response.BinaryWrite(ms.ToArray());
                    context.Response.End();
                }
            }
        }

        public void GetPureHead(HttpContext context)
        {
            string pureheadid = context.Request["pureheadid"].Trim();
            string gender = context.Request["gender"].Trim();
            Bitmap head = null;
            int headid = 0;
            int.TryParse(pureheadid, out headid);
            try
            {
                if (headid <= 0)
                {
                    if (gender == "2")
                    {
                        head = new Bitmap(context.Server.MapPath("~/Content/Image/Head/pic_f.gif"));
                    }
                    else
                    {
                        head = new Bitmap(context.Server.MapPath("~/Content/Image/Head/pic_m.gif"));
                    }
                    using (MemoryStream ms = new MemoryStream())
                    {
                        head.Save(ms, ImageFormat.Bmp);
                        context.Response.ClearContent();
                        context.Response.ContentType = "image/Gif";
                        context.Response.BinaryWrite(ms.ToArray());
                        context.Response.End();
                    }
                }
                else
                {
                    CustomFaceBO bo = new CustomFaceBO();
                    CustomFace face = bo.GetInfo(headid);
                    context.Response.ClearContent();
                    context.Response.ContentType = "image/Gif";
                    if (face != null)
                    {
                        context.Response.BinaryWrite(face.FaceImage);
                    }
                    context.Response.End();
                }
            }
            catch
            {

            }
            finally
            {
                if (head != null)
                {
                    head.Dispose();
                }
                
            }

        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}